package com.deng.eventflow.core.tmf;

import com.deng.eventflow.core.PubliclyStateful;
import com.deng.eventflow.core.SynchronousProcessor;

import java.util.Queue;

public class Trim extends SynchronousProcessor implements PubliclyStateful {
    protected final int m_delay;
    private Trim()
    {
        super(1, 1);
        m_delay = 0;
    }

    public Trim(int delay)
    {
        super(1, 1);
        m_delay = delay;
    }

    @Override
    protected boolean compute(Object[] inputs, Queue<Object[]> outputs)
    {
        if (m_inputCount >= getDelay())
        {
            outputs.add(inputs);
            if (m_eventTracker != null)
            {
                for (int i = 0; i < inputs.length; i++)
                {
                    m_eventTracker.associateToInput(getId(), i, m_inputCount, i, m_outputCount);
                }
            }
            m_outputCount++;
        }
        m_inputCount++;
        return true;
    }

    @Override
    public Trim duplicate(boolean with_state)
    {
        Trim t = new Trim(getDelay());
        if (with_state)
        {
            t.m_inputCount = m_inputCount;
            t.m_outputCount = m_outputCount;
        }
        return t;
    }

    public int getDelay()
    {
        return m_delay;
    }

    /**
     * @since 0.10.2
     */
    @Override
    protected Object printState()
    {
        return m_delay;
    }

    /**
     * @since 0.10.2
     */
    @Override
    protected Trim readState(Object o)
    {
        int delay = ((Number) o).intValue();
        return new Trim(delay);
    }

    @Override
    public Object getState()
    {
        return Math.max(0, m_delay - m_inputCount);
    }
}
